package ua.at.tsvetkov.samizdat.activities;

import ua.at.tsvetkov.application.ActivityStack;
import ua.at.tsvetkov.net.NetCheck;
import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.adapters.AdtAcAlphabet;
import ua.at.tsvetkov.samizdat.data.Data;
import ua.at.tsvetkov.samizdat.data.DataDownloader;
import ua.at.tsvetkov.samizdat.data.OnCompleteLoadListener;
import ua.at.tsvetkov.ui.Rout;
import ua.at.tsvetkov.util.Log;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

/**
 * @author A.Tsvetkov 2011, http://tsvetkov.at.ua, al@ukr.net
 */
public class AcAlphabet extends AcTemplate {

	private GridView			gridView;
	private AdtAcAlphabet	adt;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainFrame.addView(mInflater.inflate(R.layout.ac_alphabet_menu, null));
		gridView = (GridView) findViewById(R.id.AcAlphabetMenuGridView);
		dataDownloader = new DataDownloader(this, (ProgressDialog) onCreateDialog(DIALOG_LOAD), Const.URL_ALPHABET, Const.LIST_VIEW_COUNT);
		dataDownloader.setOnCompleteLoadListener(onCompleteLoadListener());
		adt = new AdtAcAlphabet(this, dataDownloader);
		gridView.setAdapter(adt);
		dataDownloader.download(Const.COUNT_ALPHABET_CHARS, Const.FILE_ALPHABET, false, false);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String[] alphaData = dataDownloader.getDataFields(position, Data.ALPHABET_FIELDS_COUNT);
				Log.i("Selected " + alphaData[Data.ALPHABET_TEXT]);
				Intent intent = new Intent(AcAlphabet.this, AcAuthors.class);
				intent.putExtra("code", alphaData[Data.ALPHABET_CODE]);
				intent.putExtra("count", alphaData[Data.ALPHABET_COUNT]);
				intent.putExtra("text", alphaData[Data.ALPHABET_TEXT]);
				startActivity(intent);
			}

		});
	}

	/**
	 * @return
	 */
	private OnCompleteLoadListener onCompleteLoadListener() {
		return new OnCompleteLoadListener() {

			@Override
			public void loadComplete(boolean isLoaded) {
				if (isLoaded) {
					AcAlphabet.this.runOnUiThread(new Runnable() {

						@Override
						public void run() {
							adt.notifyDataSetChanged();
						}
					});
				} else {
					if (!NetCheck.getInstance().isOnline()) {
						Rout.toast(ActivityStack.getLastActivity(), NetCheck.getInstance().getStatusStringRu(), Toast.LENGTH_LONG);
					} else {
						Rout.toast(ActivityStack.getLastActivity(), R.string.CONTENT_IS_ABSENT, Toast.LENGTH_LONG);
					}
					finish();
				}
			}

		};
	}

}
